<?php
namespace yan\googlebusiness;

class GoogleBusiness extends AbstractService
{
    protected static $classMap = [
        'auth'=>[
            'class'=>\yan\googlebusiness\factory\Authenticate::class,
            'client' => true
        ],
        'product'=>[
            'class'=>\yan\googlebusiness\factory\ShoppingContent::class,
            'client' => true
        ],
    ];
    private $_client;
    private $_shoppingContent;
    private $_http;
    private $merchantId;
    private $client_id;
    private $client_secret;
    private $root_url = 'https://shoppingcontent.googleapis.com';
    private $redirect_uri;
    private $product_path;
    public function init($config){
        $this->merchantId       = isset($config['merchantId']) ? $config['merchantId'] : '';
        $this->client_id        = isset($config['client_id']) ? $config['client_id'] : '';
        $this->client_secret    = isset($config['client_secret']) ? $config['client_secret'] : '';
        $this->redirect_uri       = isset($config['redirect_uri']) ? $config['redirect_uri'] : '';
        $credentials_file       = isset($config['credentials_file']) ? $config['credentials_file'] : '';
        $this->product_path     = '/content/v2.1/'.$this->merchantId.'/products';
        $client = new \Google\Client();
        $client->setApplicationName("Shopping Content");
        
        if(!empty($credentials_file) && is_file($credentials_file)){
            $client->setAuthConfig($credentials_file);
        }
        $client->setScopes($this->root_url);
        $this->_client = $client;        
    }

    public function authenticate(){
        $this->auth->authenticate($this->getClient());
    }
    public function getClient(){
        return $this->_client;
    }
    public function getShoppingContent(){
        if(empty($this->_shoppingContent)){            
            $this->_shoppingContent = new \Google\Service\ShoppingContent($this->getClient());;
        }
        return $this->_shoppingContent;
    }
    public function getRootDir(){
        return dirname(__DIR__);
    }
    
    public function getRedirectUri(){
        return $this->redirect_uri;
    }
    public function httpClient(){
        // returns a Guzzle HTTP Client
        if(empty($this->_http)){            
            $this->_http = $this->getClient()->authorize();
        }
        return $this->_http;
    }
    public function baseUrl(){
        return $this->root_url . $this->product_path;
    }
    public function getAttr($name){
        return isset($this->$name) ? $this->$name : null;
    }
}
